<template>
  <div class="login-container">
    <!-- 背景装饰元素 -->
    <div class="bg-decoration bg-decoration-1"></div>
    <div class="bg-decoration bg-decoration-2"></div>

    <div class="login-wrapper">
      <!-- 系统标题 + 副标题（进一步缩小标题） -->
      <div class="title-group">
        <h1 class="main-title">“果乐”水吧综合管理系统</h1>
        <p class="sub-title">高效管理 · 便捷操作</p>
      </div>

      <div class="login-box">
        <!-- 登录方式切换按钮 -->
        <div class="login-method-switch">
          <el-button
              type="text"
              :class="{ 'active-method': loginForm.loginMethod === 'username' }"
              @click="loginForm.loginMethod = 'username'"
          >
            <el-icon class="method-icon"><User /></el-icon>
            用户名登录
          </el-button>
          <el-button
              type="text"
              :class="{ 'active-method': loginForm.loginMethod === 'phone' }"
              @click="loginForm.loginMethod = 'phone'"
          >
            <el-icon class="method-icon"><Phone /></el-icon>
            手机号登录
          </el-button>
        </div>

        <el-form :model="loginForm" class="auth-form">
          <!-- 用户名/手机号输入框 -->
          <el-form-item prop="identifier">
            <el-input
                type="text"
                v-model="loginForm.identifier"
                :placeholder="loginForm.loginMethod === 'username' ? '输入用户名' : '输入手机号'"
                class="auth-input"
            >
              <template #prefix>
                <el-icon class="input-icon">
                  <component :is="loginForm.loginMethod === 'username' ? User : Phone" />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 密码输入框 -->
          <el-form-item prop="pswd">
            <el-input
                type="password"
                v-model="loginForm.pswd"
                placeholder="输入密码"
                class="auth-input"
            >
              <template #prefix>
                <el-icon class="input-icon"><Lock /></el-icon>
              </template>
            </el-input>
          </el-form-item>

          <!-- 验证码区域（放大图片，确保清晰可见） -->
          <el-form-item prop="captcha">
            <div class="captcha-wrapper">
              <el-input
                  type="text"
                  v-model="loginForm.captcha"
                  placeholder="    验证码"
                  class="auth-input captcha-input"
              />
              <!-- 验证码图片和换一张文字容器 -->
              <div class="captcha-reload" @click="refreshCaptcha">
                <img
                    :src="captchaImage"
                    alt="验证码"
                    class="captcha-image"
                />
                <span class="reload-text">换一张</span>
              </div>
            </div>
          </el-form-item>

          <!-- 登录按钮 -->
          <el-form-item>
            <el-button
                class="auth-button"
                @click="gotoMain"
                :loading="loading"
                type="primary"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>

        <!-- 错误提示 -->
        <div class="error-message" v-if="errorMsg">
          <el-icon class="error-icon"><WarningFilled /></el-icon>
          {{ errorMsg }}
        </div>
      </div>

      <!-- 底部版权信息 -->
      <div class="copyright">© 2025 果乐水吧 版权所有</div>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onUnmounted } from "vue";
// import { reactive, ref } from "vue";
import axios from "axios";
import qs from "qs";
import router from "@/util/router.js";
import { useUserStore } from "@/store/userStore";
import { ElIcon } from "element-plus";
import { User, Phone, Lock, WarningFilled } from "@element-plus/icons-vue";

let loginForm = reactive({
  loginMethod: "username",
  identifier: "",
  pswd: "",
  captcha: ""
});
const errorMsg = ref("");
const loading = ref(false);
const captchaImage = ref("");
// 回车登录逻辑
function handleKeyDown(e) {
  // 判断是否按下回车键（keyCode 13 或 key === 'Enter'）
  if (e.key === 'Enter' || e.keyCode === 13) {
    e.preventDefault(); // 阻止默认行为（比如表单提交刷新页面）
    gotoMain(); // 触发登录方法
  }
}

// 挂载时添加全局监听
onMounted(() => {
  window.addEventListener('keydown', handleKeyDown);
});
// 卸载时移除监听（关键！避免内存泄漏）
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyDown);
});
// 刷新验证码
function refreshCaptcha() {
  axios.get("/glsb/captcha", { responseType: "text" })
      .then((res) => {
        captchaImage.value = "data:image/png;base64," + res.data;
      })
      .catch((error) => {
        console.error('获取验证码失败:', error);
        errorMsg.value = "获取验证码失败，请稍后再试";
      });
}

// 初始加载验证码
refreshCaptcha();

// 登录逻辑（保持不变）
function gotoMain() {
  loading.value = true;
  const logindata = {
    loginMethod: loginForm.loginMethod,
    identifier: loginForm.identifier,
    password: loginForm.pswd,
    captcha: loginForm.captcha
  };
  axios
      .post("/glsb/login", qs.stringify(logindata))
      .then((res) => {
        console.log('后端返回数据:', res.data);
        let result = res.data;
        if (result && result.result === 'success') {
          let userData = result.data;
          if (userData) {
            if (!userData.token) {
              console.error('用户数据缺少 token:', userData);
              errorMsg.value = '登录失败，缺少 token';
            } else if (!userData.roleId) {
              console.error('用户数据缺少 roleId:', userData);
              errorMsg.value = '登录失败，缺少角色 ID';
            } else if (!userData.adminUserId) {
              console.error('用户数据缺少 adminUserId:', userData);
              errorMsg.value = '登录失败，缺少管理员用户 ID';
            } else {
              let userStore = useUserStore();
              userStore.setToken(userData.token);
              userStore.setUserrole(userData.roleId);
              userStore.setAdminUserId(userData.adminUserId);
              router.push({ path: "/" })
                  .then(() => console.log('路由跳转成功'))
                  .catch((err) => {
                    console.error('路由跳转失败:', err);
                    errorMsg.value = '路由跳转失败，请检查配置';
                  });
            }
          } else {
            console.error('用户数据为空:', userData);
            errorMsg.value = '登录失败，用户数据为空';
          }
        } else {
          console.error('登录失败:', result.error || '未知错误');
          errorMsg.value = result.error || '登录失败，请稍后重试';
        }
        loading.value = false;
      })
      .catch((error) => {
        console.error('网络错误:', error);
        errorMsg.value = "网络错误，请稍后再试";
        loading.value = false;
      });
}

function goToRegister() {
  router.push({ path: "/register" });
}
</script>

<style scoped>
/* 全局样式重置和基础设置 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 登录容器 */
.login-container {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, #f0f9ff, #e6f7ff);
  overflow: hidden;
}

/* 背景装饰元素 */
.bg-decoration {
  position: absolute;
  border-radius: 50%;
  background: rgba(64, 158, 255, 0.08);
  z-index: 0;
}

.bg-decoration-1 {
  width: 600px;
  height: 600px;
  top: -200px;
  left: -200px;
}

.bg-decoration-2 {
  width: 400px;
  height: 400px;
  bottom: -150px;
  right: -150px;
}

/* 登录内容包裹层 */
.login-wrapper {
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 380px;
  padding: 0 20px;
}

/* 标题组（核心调整：系统标题进一步缩小） */
.title-group {
  text-align: center;
  margin-bottom: 22px; /* 标题缩小后，间距同步减小 */
}

.main-title {
  color: #1989fa;
  font-size: 1.6rem; /* 从1.8rem缩小到1.6rem（关键调整） */
  font-weight: 600; /* 字体权重降低，更柔和 */
  margin-bottom: 5px;
  letter-spacing: 0.2px;
}

.sub-title {
  color: #64748b;
  font-size: 0.85rem; /* 副标题同步缩小 */
  opacity: 0.8;
}

/* 登录盒子 */
.login-box {
  background: #fff;
  padding: 35px 30px;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  width: 100%;
  text-align: center;
  transition: box-shadow 0.3s ease;
}

.login-box:hover {
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.12);
}

/* 登录方式切换 */
.login-method-switch {
  display: flex;
  gap: 20px;
  margin-bottom: 25px;
  border-bottom: 1px solid #f0f2f5;
  padding-bottom: 12px;
  justify-content: center;
}

.login-method-switch .el-button {
  color: #64748b;
  font-size: 17px;
  padding: 0 20px 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.login-method-switch .el-button.active-method {
  color: #1989fa;
  font-weight: 600;
  border-bottom: 2px solid #1989fa;
}

.login-method-switch .el-button:hover {
  color: #1989fa;
}

/* 表单样式 */
.auth-form {
  width: 100%;
}

/* 输入框样式 */
.auth-input {
  width: 100%;
  margin-bottom: 22px;
  height: 50px;
  border-radius: 10px;
  border: 1px solid #e5e7eb;
  font-size: 15px;
  transition: all 0.3s ease;
}

.auth-input:focus {
  outline: none;
  border-color: #1989fa;
  box-shadow: 0 0 0 3px rgba(25, 137, 250, 0.1);
}

/* 输入框图标 */
.input-icon {
  width: 22px;
  height: 22px;
  font-size: 22px;
  color: #94a3b8;
}

/* ------------- 验证码区域核心调整（放大图片，确保清晰） ------------- */
.captcha-wrapper {
  display: flex;
  align-items: center;
  gap: 8px; /* 间距适中，不拥挤 */
}

.captcha-input {
  flex: 1;
  margin-bottom: 0;
}

/* 放大验证码图片，确保完全显示且清晰（关键调整） */
.captcha-image {
  width: 120px; /* 从70px放大到90px，兼顾大小和布局 */
  height: 45px; /* 从32px放大到38px，比例协调 */
  border-radius: 8px;
  object-fit: contain; /* 确保图片完整显示，不裁剪（核心） */
  border: 1px solid #e5e7eb;
  transition: all 0.2s ease;
  background-color: #fff; /* 白色背景，避免透明验证码显示异常 */
  padding: 2px; /* 轻微内边距，让验证码更舒展 */
}

.captcha-image:hover {
  transform: scale(1.03); /* hover轻微放大，方便查看细节 */
}

/* 验证码和换一张文字容器 */
.captcha-reload {
  display: flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
}

/* 换一张文字样式 */
.reload-text {
  color: #1989fa;
  font-size: 13px;
  user-select: none;
  font-weight: 500;
  transition: all 0.3s ease;
}

.reload-text:hover {
  text-decoration: underline;
  color: #0d76ff;
}
/* ------------- 验证码区域调整结束 ------------- */

/* 登录按钮 */
.auth-button {
  width: 100%;
  height: 52px;
  border-radius: 10px;
  font-size: 17px;
  font-weight: 600;
  background-color: #1989fa;
  border: none;
  transition: all 0.3s ease;
}

.auth-button:hover {
  background-color: #0d76ff;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(25, 137, 250, 0.2);
}

.auth-button:active {
  transform: translateY(0);
}

/* 错误提示 */
.error-message {
  color: #ef4444;
  margin-top: 18px;
  font-size: 14px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 12px;
  border-radius: 8px;
  background-color: rgba(239, 68, 68, 0.05);
}

.error-icon {
  width: 16px;
  height: 16px;
}

/* 登录方式切换按钮图标 */
.method-icon {
  margin-right: 8px;
  width: 20px;
  height: 20px;
  font-size: 20px;
}

/* 底部版权信息 */
.copyright {
  margin-top: 25px;
  color: #94a3b8;
  font-size: 12px;
  opacity: 0.8;
  text-align: center;
}

/* 图标容器样式 */
:deep(.el-icon) {
  vertical-align: middle;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 适配小屏幕 */
@media (max-width: 375px) {
  .login-box {
    padding: 28px 20px;
  }

  .main-title {
    font-size: 1.4rem; /* 小屏幕标题再缩小 */
  }

  .auth-input {
    height: 46px;
  }

  .auth-button {
    height: 48px;
  }

  /* 小屏幕验证码适配（避免溢出） */
  .captcha-image {
    width: 80px;
    height: 36px;
  }

  .reload-text {
    font-size: 12px;
  }
}
</style>